import React, { useEffect, useRef } from 'react'
import styles from './index.module.scss'
import { EditOutlined, DeleteOutlined } from '@ant-design/icons'
import {
  Card,
  Breadcrumb,
  Form,
  Radio,
  DatePicker,
  Select,
  Button,
  Table,
  Tag,
  Image,
  Space,
  Popconfirm,
  message,
} from 'antd'
import { Link, useHistory } from 'react-router-dom'
import { useDispatch, useSelector } from 'react-redux'
import { del, getArticleList, getChannelList } from '@/store/actions/article'
import error from '@/assets/error.png'
export default function Article() {
  const history = useHistory()

  // 1.获取频道列表
  const dispatch = useDispatch()
  useEffect(() => {
    // 2.获取频道列表
    dispatch(getChannelList())
    dispatch(getArticleList())
  }, [dispatch])
  // 3.获取所有频道
  const channelList = useSelector((state) => state.article.channels)
  // 4. 筛选
  const params = useRef({})
  // let params.current={}
  const onFinish = (values) => {
    if (values.status !== -1) {
      params.current.status = values.status
    } else {
      // 清除之前的值  因为存储到current中了 所以点击其他的 就不会再走if
      delete params.current.status
    }
    if (values.date) {
      params.current.begin_pubdate = values.date[0]
        .startOf('day')
        .format('YYYY-MM-DD HH:mm:ss')
      params.current.end_pubdate = values.date[1]
        .startOf('day')
        .format('YYYY-MM-DD HH:mm:ss')
    } else {
      delete params.current.begin_pubdate
      delete params.current.end_pubdate
    }
    if (values.channel_id) {
      params.current.channel_id = values.channel_id
    }
    // console.log(params.current)
    // 筛选 页码修改为1 筛选的时候可能在其他页码例如在第3页 但是如果数据没有20多条那么 就会出问题此时就把页码设置为1
    params.current.page = 1
    dispatch(getArticleList(params.current))
  }
  // 4.1获取文章列表
  const articlelList = useSelector((state) => state.article.articles)
  // 6. const
  const STATUS = [
    { id: -1, title: '全部', color: 'red' },
    { id: 0, title: '草稿', color: 'blue' },
    { id: 1, title: '待审核', color: 'orange' },
    { id: 2, title: '审核通过', color: 'green' },
    { id: 3, title: '审核失败', color: 'yellow' },
  ]
  // 7. 删除
  const confirm = async (id) => {
    // 1.删除
    await dispatch(del(id))
    // 2.等待删除完之后重新获取数据渲染 也要把筛选条件传递进来
    if (articlelList.results.length === 1 && articlelList.page > 1) {
      params.current.page = articlelList.page - 1
    }
    await dispatch(getArticleList(params.current))
    // 3.提示删除成功
    message.success('删除成功')
  }
  // 5.表格
  const columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      render: (cover) => {
        if (cover.type === 0) {
          return <Image width={50} height={50} src={error} />
        } else {
          return <Image width={50} height={50} src={cover.images[0]} />
        }
      },
    },
    {
      title: '标题',
      dataIndex: 'title',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (status) => {
        const flag = STATUS.find((item) => item.id === status)
        return <Tag color={flag.color}>{flag.title}</Tag>
      },
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
    },
    {
      title: '操作',
      dataIndex: 'id',
      render: (id) => {
        return (
          <Space>
            <Button
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
              onClick={() => {
                history.push(`/home/publish/${id}`)
              }}
            ></Button>
            <Popconfirm
              title="你确定删除该文章吗?"
              onConfirm={() => {
                confirm(id)
              }}
            >
              <Button
                type="danger"
                shape="circle"
                icon={<DeleteOutlined />}
              ></Button>
            </Popconfirm>
          </Space>
        )
      },
    },
  ]
  //8 处理分页
  // 9.改变页码或 每页显示的条数
  return (
    <div className={styles.root}>
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>文章列表</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form
          onFinish={onFinish}
          name="basic"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ status: -1 }}
        >
          <Form.Item label="状态" name="status">
            <Radio.Group>
              {STATUS.map((item) => (
                <Radio value={item.id} key={item.id}>
                  {item.title}
                </Radio>
              ))}
            </Radio.Group>
          </Form.Item>
          <Form.Item label="频道" name="channel_id">
            <Select placeholder="请选择频道" style={{ width: 400 }} allowClear>
              {channelList.map((item) => (
                <Select.Option value={item.id} key={item.id}>
                  {item.name}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item label="日期" name="date">
            <DatePicker.RangePicker />
          </Form.Item>
          <Form.Item wrapperCol={{ span: 16, offset: 4 }}>
            <Button type="primary" htmlType="submit">
              筛选
            </Button>
          </Form.Item>
        </Form>
      </Card>
      {/* 表格 */}
      <Card
        style={{ marginTop: 10 }}
        title={`根据筛选条件共查询到 ${articlelList.total_count} 条结果：`}
      >
        <Table
          rowKey="id"
          columns={columns}
          dataSource={articlelList.results}
          pagination={{
            position: ['bottomCenter'],
            current: articlelList.page,
            pageSize: articlelList.per_page,
            onChange: function (page, pageSize) {
              if (pageSize !== articlelList.per_page) {
                params.current.page = 1
                params.current.per_page = pageSize
              } else {
                params.current.page = page
              }
              // console.log(page)
              dispatch(getArticleList(params.current))
            },

            total: articlelList.total_count,
          }}
        />
      </Card>
    </div>
  )
}
